package cn.tongji.edu.tjmobile;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.tongji.edu.tjmobile.component.ActionSheet;

public class MainActivity extends FragmentActivity implements ActionSheet.ActionSheetListener {

    public static String userName;
    public static String userId;

    private static String MOBILE_LIBRARY_HOMEPAGE_URL = "http://www.lib.tongji.edu.cn/site/tongji/index.html";
    private static String MOBILE_LIBRARY_WEIBO_URL = "http://weibo.com/tongjiunivlibrary";
    private static String MOBILE_LIBRARY_PHONE_HOMEPAGE_URL = "http://www.lib.tongji.edu.cn/m/index.action";

    private static String SCHOOL_FRIEND_HOMEPAGE_URL = "http://www.tongjiren.org";
    private static String SCHOOL_FRIEND_WEIBO_URL = "http://weibo.com/tongjiren";

    private static String TONGJI_OFFICIAL_HOMEPAGE_URL = "http://www.tongji.edu.cn/";
    private static String TONGJI_OFFICIAL_WEIBO_URL = "http://weibo.com/tongjiuniversity";

    private static String TEACHER_OA_URL = "http://www.weaver.com.cn/emobile";

    private DrawerLayout drawerLayout;
    private FrameLayout contentFrame;
    private LinearLayout menuLayout;
    private ActionBarDrawerToggle drawerToggle;

    private View tongjiAppLayout;
    private View personalCenterLayout;

    private CurrentActionSheet currentActionSheet;

    private ActionSheet.Builder mobileLibraryActionSheet;
    private ActionSheet.Builder schoolFriendActionSheet;
    private ActionSheet.Builder tongjiOfficialActionSheet;

    private boolean isLogin = false;

    public enum CurrentActionSheet {
        MOBILE_LIBRARY, SCHOOL_FRIEND, TEACHER_OA, TONGJI_OFFICIAL, YOUTH_TONGJI
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = getIntent();
        isLogin = intent.getBooleanExtra("isLogin", false);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        contentFrame = (FrameLayout) findViewById(R.id.content_frame);

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        tongjiAppLayout = inflater.inflate(R.layout.tongji_app, null);
        personalCenterLayout = inflater.inflate(R.layout.personal_center, null);
        contentFrame.addView(tongjiAppLayout);

        menuLayout = (LinearLayout) findViewById(R.id.left_drawer);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        initHamburgerButton();
        initTongjiAppPanel();

        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
                R.drawable.ic_launcher, R.string.app_name, R.string.app_name) {
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }
        };
        drawerLayout.setDrawerListener(drawerToggle);

        if(isLogin) {
            FileInputStream avatarIn = null;
            try {
                File avatarFile = new File("/sdcard/TJMobile/avatar.png");
                if (avatarFile.exists()) {
                    avatarIn = new FileInputStream(avatarFile);
                    Bitmap bitmap = BitmapFactory.decodeStream(avatarIn);
                    ImageView avatarView = (ImageView) findViewById(R.id.drawer_avatar);
                    avatarView.setImageBitmap(bitmap);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (avatarIn != null) {
                        avatarIn.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        final RelativeLayout tongjiAppMenu = (RelativeLayout) findViewById(R.id.tongji_app_menu);
        tongjiAppMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contentFrame.removeAllViews();
                contentFrame.addView(tongjiAppLayout);
                drawerLayout.closeDrawer(Gravity.LEFT);
                initHamburgerButton();
            }
        });

        final RelativeLayout personalCenterMenu = (RelativeLayout) findViewById(R.id.personal_center_menu);
        personalCenterMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin) {
                    contentFrame.removeAllViews();
                    contentFrame.addView(personalCenterLayout);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                    initHamburgerButton();
                    TextView tjLabelTextView = (TextView) findViewById(R.id.tj_label_user_name);
                    tjLabelTextView.setText(userName);

                    RelativeLayout changeAvatarButton = (RelativeLayout) findViewById(R.id.change_avatar_button);
                    RelativeLayout changeCoverButton = (RelativeLayout) findViewById(R.id.change_cover_button);

                    loadAvatarAndCover();

                    changeAvatarButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent, 1);
                        }
                    });
                    changeCoverButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent, 2);
                        }
                    });
                } else {
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, LoginFormActivity.class);
                    startActivity(intent);
                }
            }
        });

        TextView userNameTextView = (TextView) findViewById(R.id.user_name_textview);
        userNameTextView.setText(userName);

        mobileLibraryActionSheet = ActionSheet.createBuilder(this, getSupportFragmentManager()).setCancelButtonTitle("取消").setOtherButtonTitles("主页", "微信", "微博", "移动版主页").setCancelableOnTouchOutside(true).setListener(this);
        schoolFriendActionSheet = ActionSheet.createBuilder(this, getSupportFragmentManager()).setCancelButtonTitle("取消").setOtherButtonTitles("主页", "微信", "微博").setCancelableOnTouchOutside(true).setListener(this);
        tongjiOfficialActionSheet = ActionSheet.createBuilder(this, getSupportFragmentManager()).setCancelButtonTitle("取消").setOtherButtonTitles("主页", "微博").setCancelableOnTouchOutside(true).setListener(this);
    }

    private void loadAvatarAndCover() {
        FileInputStream avatarIn = null;
        FileInputStream coverIn = null;
        try {
            File avatarFile = new File("/sdcard/TJMobile/avatar.png");
            if (avatarFile.exists()) {
                avatarIn = new FileInputStream(avatarFile);
                Bitmap bitmap = BitmapFactory.decodeStream(avatarIn);
                ImageView avatarView = (ImageView) findViewById(R.id.personal_avatar_image);
                avatarView.setImageBitmap(bitmap);
            }

            File coverFile = new File("/sdcard/TJMobile/cover.png");
            if (coverFile.exists()) {
                coverIn = new FileInputStream(coverFile);
                Bitmap bitmap = BitmapFactory.decodeStream(coverIn);
                LinearLayout coverView = (LinearLayout) findViewById(R.id.personal_cover_image);
                coverView.setBackground(new BitmapDrawable(bitmap));
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (avatarIn != null) {
                    avatarIn.close();
                }
                if (coverIn != null) {
                    coverIn.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                ContentResolver cr = this.getContentResolver();
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                    ImageView avatarView = (ImageView) findViewById(R.id.personal_avatar_image);
                    avatarView.setImageBitmap(bitmap);
                    saveImageFile(bitmap, "/sdcard/TJMobile/avatar.png");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == 2) {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                ContentResolver cr = this.getContentResolver();
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                    LinearLayout coverView = (LinearLayout) findViewById(R.id.personal_cover_image);
                    coverView.setBackground(new BitmapDrawable(bitmap));
                    saveImageFile(bitmap, "/sdcard/TJMobile/cover.png");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initHamburgerButton() {
        ImageView hamburgerView = (ImageView) findViewById(R.id.image_hamburger);
        hamburgerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(Gravity.LEFT);
            }
        });
    }

    private void saveImageFile(Bitmap bitmap, String path) {
        File directory = new File("/sdcard/TJMobile/");
        if (!directory.exists()) {
            directory.mkdir();
        }
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void initTongjiAppPanel() {
        ImageView busImage = (ImageView) findViewById(R.id.bus_image);
        busImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin) {
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, ReserveBusActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, LoginFormActivity.class);
                    startActivity(intent);
                }
            }
        });

        ImageView mobileLibraryImage = (ImageView) findViewById(R.id.mobile_library_image);
        mobileLibraryImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentActionSheet = CurrentActionSheet.MOBILE_LIBRARY;
                mobileLibraryActionSheet.show();
            }
        });

        ImageView schoolFriendImage = (ImageView) findViewById(R.id.school_friend_image);
        schoolFriendImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentActionSheet = CurrentActionSheet.SCHOOL_FRIEND;
                schoolFriendActionSheet.show();
            }
        });

        ImageView teacherOAImage = (ImageView) findViewById(R.id.teacher_oa_image);
        teacherOAImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri contentUrl = Uri.parse(TEACHER_OA_URL);
                intent.setData(contentUrl);
                startActivity(intent);
            }
        });

        ImageView tongjiOfficialImage = (ImageView) findViewById(R.id.tongji_official_image);
        tongjiOfficialImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentActionSheet = CurrentActionSheet.TONGJI_OFFICIAL;
                tongjiOfficialActionSheet.show();
                ;
            }
        });

        ImageView youthTongjiImage = (ImageView) findViewById(R.id.youth_tongji_image);
        youthTongjiImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("qrcode_image", CurrentActionSheet.YOUTH_TONGJI);
                intent.putExtra("wechat_description", "同济大学团委—青春同济");
                intent.putExtra("wechat_id", "qctjwx");
                intent.setClass(MainActivity.this, WechatActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

    }

    @Override
    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
        switch (currentActionSheet) {
            case MOBILE_LIBRARY:
                if (index == 0) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri contentUrl = Uri.parse(MOBILE_LIBRARY_HOMEPAGE_URL);
                    intent.setData(contentUrl);
                    startActivity(intent);
                } else if (index == 1) {
                    Intent intent = new Intent();
                    intent.putExtra("qrcode_image", CurrentActionSheet.MOBILE_LIBRARY);
                    intent.putExtra("wechat_description", "同济大学图书馆信息服务");
                    intent.putExtra("wechat_id", "tongji-lib");
                    intent.setClass(MainActivity.this, WechatActivity.class);
                    startActivity(intent);
                } else if (index == 2) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri contentUrl = Uri.parse(MOBILE_LIBRARY_WEIBO_URL);
                    intent.setData(contentUrl);
                    startActivity(intent);
                } else if (index == 3) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri contentUrl = Uri.parse(MOBILE_LIBRARY_PHONE_HOMEPAGE_URL);
                    intent.setData(contentUrl);
                    startActivity(intent);
                }
                break;
            case SCHOOL_FRIEND:
                if (index == 0) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri contentUrl = Uri.parse(SCHOOL_FRIEND_HOMEPAGE_URL);
                    intent.setData(contentUrl);
                    startActivity(intent);
                } else if (index == 1) {
                    Intent intent = new Intent();
                    intent.putExtra("qrcode_image", CurrentActionSheet.SCHOOL_FRIEND);
                    intent.putExtra("wechat_description", "同济大学校友会");
                    intent.putExtra("wechat_id", "TONGJI-xyh");
                    intent.setClass(MainActivity.this, WechatActivity.class);
                    startActivity(intent);
                } else if (index == 2) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri contentUrl = Uri.parse(SCHOOL_FRIEND_WEIBO_URL);
                    intent.setData(contentUrl);
                    startActivity(intent);
                }
                break;
            case TONGJI_OFFICIAL:
                if (index == 0) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri contentUrl = Uri.parse(TONGJI_OFFICIAL_HOMEPAGE_URL);
                    intent.setData(contentUrl);
                    startActivity(intent);
                } else if (index == 1) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri contentUrl = Uri.parse(TONGJI_OFFICIAL_WEIBO_URL);
                    intent.setData(contentUrl);
                    startActivity(intent);
                }
                break;
        }
    }
}